package com.ruoyi.quartz.task;

/**
 * @author wuxiao
 * @Package com.ruoyi.quartz.task
 * @date 2025-09-29 11:10
 */
import com.ruoyi.system.domain.BusInsomniaAlert;
import com.ruoyi.system.service.IBusInsomniaAlertService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 每天定时查询当天的失眠预警，并通过邮件发送
 */
@Component("insomniaAlertMailTask")
public class InsomniaAlertMailTask {

    @Autowired
    private JavaMailSender mailSender;


    @Autowired
    private IBusInsomniaAlertService insomniaAlertService;


    @Value("${spring.mail.username}")  // 从 yml 读取发件人
    private String fromMail;

    /**
     * 定时执行方法（例如每天早上 9 点）
     */
    public void sendTodayAlerts(String userId,String toMail) {
        try {
            // 获取当天日期字符串
            String todayStr = new SimpleDateFormat("yyyy-MM-dd").format(new Date());

            // 查询当天的预警（需要你的 service 根据日期筛选，下面只是示例）
            BusInsomniaAlert query = new BusInsomniaAlert();
            query.setCreateTime(new Date()); //  建议改成 between 00:00-23:59 查询当天
            query.setUserId(Long.parseLong(userId)); //  建议改成 between 00:00-23:59 查询当天
            List<BusInsomniaAlert> alerts = insomniaAlertService.selectBusInsomniaAlertList(query);

            if (alerts == null || alerts.isEmpty()) {
                System.out.println("今天没有失眠预警信息。");
                return;
            }

            // 拼接预警信息内容
            StringBuilder sb = new StringBuilder();
            sb.append("【").append(todayStr).append(" 失眠预警信息】\n\n");
            for (BusInsomniaAlert alert : alerts) {
                sb.append("用户ID: ").append(alert.getUserId()).append("\n")
                        .append("预警类型: ").append(alert.getAlertType()).append("\n")
                        .append("预警等级: ").append(alert.getAlertLevel()).append("\n")
                        .append("提示信息: ").append(alert.getAlertMessage()).append("\n")
                        .append("时间: ").append(alert.getCreateTime()).append("\n")
                        .append("-------------------------\n");
            }

            String message = sb.toString();
            System.out.println("发送邮件内容：\n" + message);

            // 发送邮件（收件人可从配置或数据库读取）
            sendEmail(toMail, todayStr + " 失眠预警信息", message);

        } catch (Exception e) {
            System.err.println("发送预警邮件失败: " + e.getMessage());
        }
    }

    /**
     * 发送邮件
     */
    private void sendEmail(String to, String subject, String text) {
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setFrom(fromMail); // 必须和 spring.mail.username 一致
        mailMessage.setTo(to);
        mailMessage.setSubject(subject);
        mailMessage.setText(text);
        mailSender.send(mailMessage);
    }
}
